package com.somlsis.activity

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import androidx.recyclerview.widget.GridLayoutManager
import com.aones.ui.adapter.AddImageAdapter
import com.base.BaseActivity
import com.base.utils.ToastUtils
import com.donkingliang.imageselector.utils.ImageSelector
import com.net.HttpResponse
import com.somlsis.R
import com.somlsis.bean.Upload
import com.somlsis.databinding.ActivityFeedbackBinding
import com.somlsis.interf.UploadCallBack
import kotlinx.coroutines.MainScope
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


class FeedbackActivity : BaseActivity<ActivityFeedbackBinding>(),
    AddImageAdapter.OnImageItemClickListener {
    private lateinit var addImageAdapter: AddImageAdapter
    private val mRequestCode = 101
    private  val mainScope = MainScope()
    override fun getViewBinding(): ActivityFeedbackBinding {
        return ActivityFeedbackBinding.inflate(LayoutInflater.from(this))
    }


    override fun createView() {
        binding.layoutTitle.title.text = getString(R.string.questions_and_comments)
        binding.layoutTitle.back.setOnClickListener {
            finish()
        }
        binding.feedbackInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence?,
                start: Int,
                count: Int,
                after: Int
            ) {
                s?.let {
                    if (it.length >= 200) {
                        ToastUtils.showTost(
                            context,
                            getString(R.string.hint_problem_description_or_suggestion)
                        )
                    }
                }
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                refreshUI()
            }

        })
        addImageAdapter = AddImageAdapter(this, this)
        var manager = GridLayoutManager(this, 4)
        binding.feedbackImage.layoutManager = manager
        binding.feedbackImage.adapter = addImageAdapter

        binding.feedbackSubmit.setOnClickListener {
            val feedbackText = binding.feedbackInput.text.toString()
            val datas = addImageAdapter.dataList
            var number = binding.feedbackNumber.text.toString()

            if (number.isEmpty()) {
                dataCenter.getUser()?.let {
                    number = it.phone
                }
            }
            if (datas.size > 0 || feedbackText.isNotEmpty()) {
                if (datas.size > 0) {
                  dataCenter.upload(datas,object :UploadCallBack{
                      override fun onUploadSucceed(urlList: ArrayList<String>) {
                          submitFeedback(urlList)
                      }

                      override fun onUploadFailure() {
                      }

                  })
                }
            } else {
                ToastUtils.showTost(
                    context,
                    getString(R.string.hint_problem_description_or_suggestion)
                )
            }
        }
    }

    private fun refreshUI() {
        val feedbackInput = binding.feedbackInput.text.toString().trim()
        if (feedbackInput.isNotEmpty()) {
            binding.feedbackSubmit.setBackgroundResource(R.drawable.shape_3f8cff_16)
            binding.feedbackSubmit.isClickable = true
        } else {
            binding.feedbackSubmit.setBackgroundResource(R.drawable.shape_c7c7c7_16)
            binding.feedbackSubmit.isClickable = false
        }
    }

    override fun onItemClick(size: Int, position: Int) {
        if (position == size && size < 9) {
            //限数量的多选(比如最多9张)
            ImageSelector.builder()
                .useCamera(true) // 设置是否使用拍照
                .setSingle(false)  //设置是否单选
                .setMaxSelectCount(9) // 图片的最大选择数量，小于等于0时，不限数量。
                .setSelected(addImageAdapter.dataList) // 把已选的图片传入默认选中。
                .canPreview(true) //是否可以预览图片，默认为true
                .start(this, mRequestCode); // 打开相册
        }
    }

    override fun onItemDeleteClick(position: Int) {
        addImageAdapter.removeData(position)
    }

    private fun submitFeedback(dataList: ArrayList<String>) {
        val feedbackText = binding.feedbackInput.text.toString()
        var feedbackType = "dysfunction"
        when (binding.feedbackType.checkedRadioButtonId) {
            R.id.dysfunction ->
                feedbackType = "dysfunction"

            R.id.comments_and_suggestions ->
                feedbackType = "comments_and_suggestions"

            R.id.other ->
                feedbackType = "other"
        }
        val number = binding.feedbackNumber.text.toString()
        dataCenter.submitFeedback(
            feedbackType,
            feedbackText,
            number,
            dataList,
            object : Callback<HttpResponse<String>> {
                override fun onResponse(
                    call: Call<HttpResponse<String>>,
                    response: Response<HttpResponse<String>>
                ) {
                    ToastUtils.showTost(
                        context,
                        response.message()
                    )
                    finish()
                }

                override fun onFailure(call: Call<HttpResponse<String>>, t: Throwable) {
                    ToastUtils.showTost(
                        context,
                        t.message
                    )
                }

            })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        data?.let {
            if (requestCode == mRequestCode) {
                //获取选择器返回的数据
                /**
                 * 是否是来自于相机拍照的图片，
                 * 只有本次调用相机拍出来的照片，返回时才为true。
                 * 当为true时，图片返回的结果有且只有一张图片。
                 */
                val isCameraImage = it.getBooleanExtra(ImageSelector.IS_CAMERA_IMAGE, false)
                val list = it.getStringArrayListExtra(
                    ImageSelector.SELECT_RESULT
                )
                list?.let { dataList ->
                    addImageAdapter.setData(dataList)
                    refreshUI()
                }
            }
        }

    }
}